package cn.org.hentai.jtt1078.subscriber;

import cn.org.hentai.jtt1078.codec.MP3Encoder;
import cn.org.hentai.jtt1078.flv.AudioTag;
import cn.org.hentai.jtt1078.flv.FlvAudioTagEncoder;
import cn.org.hentai.jtt1078.flv.FlvEncoder;
import cn.org.hentai.jtt1078.util.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;

/**
 * （通过ffmpeg子进程将http-flv另外传输一份到RTMP服务器的实现）
 */
public class RTMPPublisher extends Thread {
    static Logger logger = LoggerFactory.getLogger(RTMPPublisher.class);

    String tag = null;
    Process process = null;

    public RTMPPublisher(String tag) {
        this.tag = tag;
    }

    //直播拉流
    @Override
    public void run() {
        InputStream stderr = null;
        int len = -1;
        byte[] buff = new byte[512];
        boolean debugMode = "on".equalsIgnoreCase(Configs.get("debug.mode"));//为on时，控制台将输出ffmpeg的输出

        try {
            String rtmpUrl = Configs.get("rtmp.url").replaceAll("\\{TAG\\}", tag);

            //ffmpeg  -i http://localhost:3333/video/13800138999-2 -vcodec copy -acodec aac -f flv rtmp://172.0.0.1/live/13800138999-2
            String cmd = String.format("%s -i http://localhost:%d/video/%s -vcodec copy -acodec aac -f flv %s",
                        Configs.get("ffmpeg.path"),
                        Configs.getInt("server.http.port", 3333),
                        tag,
                        rtmpUrl
                    );

            //Runtime.getRuntime().exec()方法主要用于执行外部的程序或命令。  方法: Process exec(String command) 在单独的进程中执行指定的字符串命令。
            logger.info("Execute: {}", cmd);
            process = Runtime.getRuntime().exec(cmd);
            stderr = process.getErrorStream(); //用于获取进程或子进程的错误流
            while ((len = stderr.read(buff)) > -1) {
                if (debugMode) System.out.print(new String(buff, 0, len));
            }
            logger.info("Process FFMPEG exited...");
        }
        catch(Exception ex) {
            logger.error("publish failed", ex);
        }
    }

    public void close() {
        try { if (process != null) process.destroyForcibly(); } catch(Exception e) { }
    }
}